###########################################################################################################
#### Replication Materials for "Affective polarization is uniformly distributed across American states ####
#### Authors: Derek E. Holliday, Yphtach Lelkes, and Sean J. Westwood                                  ####
#### Last Updated: 07/31/2024                                                                          ####
#### R Version: 4.2.2                                                                                  ####
###########################################################################################################

# Uncomment below to install package `librarian`
# install.package("librarian")

# Load/Install necessary packages
librarian::shelf(tidyverse, here, rio, srvyr, tidymodels, kableExtra, 
                 usmap, patchwork, lme4, ggthemes, doParallel)

# Pathing instructions:
# Create an R project in the top directory, where Code, Data, Output, and Plots are subdirectories
# here() will navigate to the parent directory, where this file "00_master.R" should be housed

# Load helper functions
sx = \(x) suppressWarnings(source(x, print.eval = T))
sx(here("Code","funcs_theme.R"))
sx(here("Code","funcs_facet_wrap_equal.R"))

# Load Data
data = import(here("Data","survey_data.rds"))

#### Main Manuscript Figures / Tables ####

## Figure 1: Distribution of Affective Polarization
sx(here("Code","figure_1.R"))

## Table 1: Geographic Variables
sx(here("Code","table_1.R"))

## Figure 2: OLS Coefficients
sx(here("Code","figure_2.R"))

## Figure 3: Random Forest Performance
# NOTE: Random forest models take hours to compile. For convenience, an intermediary
# file is created for the RF output ("rf_output.rds") in the Output folder.
sx(here("Code","figure_3.R"))


#### Supplementary Figures ####

## Figures S1 and S2: Weighting
sx(here("Code","figure_s1-2.R"))

## Figures S3: Random Forest Robustness
# NOTE: Random forest models take hours to compile. For convenience, an intermediary
# file is created for the RF output ("rf_output_cat.rds") in the Output folder.
sx(here("Code","figure_s3.R"))

## Figure S4: Predicted Value Robustness
sx(here("Code","figure_s4.R"))